home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / Libraries / VideoToolbox 96.06.15 / VideoToolboxSources / Shuffle.c < prev    next >
Text File  |  1995-07-19  |  1KB  |  38 lines

  1. /*
  2. Shuffle.c
  3. Like the Standard C function qsort(), Shuffle reorders the elements of
  4. an array, but Shuffle produces a randomized sequence.
  5.  
  6. HISTORY:
  7. 3/19/94    dgp    rewrote it to accept an arbitrary element size. It probably now
  8. runs ten times slower than when it only accepted shorts. If the loss of speed
  9. matters to anybody, let me know, as it would be easy to add fast special-case
  10. code for a few popular element sizes, e.g. sizeof(short).
  11. */
  12. #include "VideoToolbox.h"
  13.  
  14. void Shuffle(void *array,long elements,size_t elementSize)
  15. {
  16.     long i,j;
  17.     void *scratch;
  18.     double workArea[256/sizeof(double)];
  19.     
  20.     assert(sizeof(char)==1);
  21.     #if MAC_C
  22.         assert(StackSpace()>4000);
  23.     #endif
  24.     if(sizeof(workArea)<elementSize){
  25.         scratch=malloc(elementSize);
  26.         assert(scratch!=NULL);
  27.     }else scratch=workArea;
  28.     for(i=0;i<elements;i++){
  29.         j=nrand(elements);
  30.         if(i==j)continue;
  31.         /* swap i-th and j-th elements */
  32.         memcpy(scratch,(char *)array+j*elementSize,elementSize);
  33.         memcpy((char *)array+j*elementSize,(char *)array+i*elementSize,elementSize);
  34.         memcpy((char *)array+i*elementSize,scratch,elementSize);
  35.     }
  36.     if(scratch!=workArea)free(scratch);
  37. }
  38.